import { Api } from "../../api/api";
import { PostUtils } from "@/components/post_item/post_add_sell_dto";
import check_utils from "./check_utils";
import { CustomDict } from "./custom_dict";
import { CustomTips } from "./custom_tips";
import { Dict } from "./dict";
import { CustomDate } from "./custom_date";

// mixin.js

export const commonMixin = {
  methods: {
    navToPage(url) {
      uni.navigateTo({
        url: url
      })
    },
    redirectToPage(url) {
      uni.redirectTo({
        url: url
      })
    },
    updateUserRole: function (roleId) {
      uni.setStorageSync('userRoleId', roleId)
      return;
    },
    getUserRole: function () {
      let userRoleId = uni.getStorageSync('userRoleId')
      if (!userRoleId) {
        uni.setStorageSync('userRoleId', Dict.PostMainTypeEnum.Shop.childs.ShopBuy.value)
        return Dict.PostMainTypeEnum.Shop.childs.ShopBuy.value
      }
      return userRoleId
    },
    isFirstLogin: function () {
      return uni.getStorageSync('firstLogin') !== 1
    },
    isMyPost: function (postDto) {
      return postDto.userId == this.$store.state.sessionDto.userDto.userId
    },
    // 面积要求
    buyAcreage(postDto) {
      if (postDto.upperAcreage >= 10000) {
        return '不限'
      } else {
        return postDto.lowerAcreage + '-' + postDto.upperAcreage + '㎡'
      }
    },
    // 租金要求
    buyRent(postDto) {
      return CustomDict.getRentDesc(postDto.lowerRent, postDto.upperRent)
    },
    buyTitle(postDto) {
      return '求租' + postDto.area + postDto.street + '的店铺'
    },
    sellTitle(postDto) {
      let industryName = CustomDict.getDictName(postDto.industryId, Dict.IndustryTypeEnum)
      console.log('解析出行业名称', this.item.industryId, industryName)
      return postDto.street + industryName + '转店'
    },
    sellTitleByArea(postDto) {
      let industryName = CustomDict.getDictName(postDto.industryId, Dict.IndustryTypeEnum)
      console.log('解析出行业名称', postDto.industryId, industryName)
      return postDto.area + postDto.street + industryName + '转店'
    },
    messageCount() {
      let count = this.$store.state.sessionDto.unreadCommentNumber + this.$store.state.sessionDto.metricRecordDtoMap.beenAddCollectNumber
      console.log('消息未读数', count)
      return count
    },
    getSimpleAmount(simpleAmount) {
      return CustomDict.getSimpleRent(simpleAmount)
    },
    getSimpleAmountValue(simpleAmount) {
      return CustomDict.getSimpleRentValue(simpleAmount)
    },
    getSimpleAmountUnit(simpleAmount) {
      return CustomDict.getSimpleRentUnit(simpleAmount)
    },
	isMember(){
		let that = this
		const memberLevel = that.$store.state.sessionDto.userDto.memberLevel
		const memberExpireDate = that.$store.state.sessionDto.userDto.memberExpireDate
		return Dict.MemberLevelEnum.Ordinary.value == memberLevel 
		&& CustomDate.calSecondsFromDate(memberExpireDate) < 0 
	},

    toMakePhone(item) {
      // 记录埋点
      Api.TrackApi.trackAdd(this, {
        userId: uni.getStorageSync('userId'),
        targetUserId: item.userId,
        recordId: item.id,
        extendInfo: CustomDict.TraceEventType.BtnAddContact.name,
        eventType: CustomDict.TraceEventType.BtnAddContact.value,
        trackCount: 1
      }, (res) => {

      })

      let that = this
      if(!PostUtils.canCommentOrContact(item)){
        return
      }
      // if (item.userDto.userId < 10000000000) {
      //   this.showCustomModal({
      //     content: CustomTips.tipsNoContactPhone,
      //     cancelColor: '#666666',
      //     cancelText: '',
      //     confirmColor: 'rgba(0, 0, 0, 0.85)',
      //     confirmText: '确定',
      //     success: function (res) {
      //       if (res.confirm) {
      //         console.log('点击了确定', res)
      //         that.hideCustomModal()
      //       } else if (res.cancel) {
      //         console.log('用户取消注销');
      //       }
      //     }
      //   })
      //   return
      // }
      uni.makePhoneCall({
        // 手机号 这里可以直接写号码如 12345 也可以写获取号码的字段如this.mobile
        phoneNumber: item.contactPhone,
        // 成功回调
        success: (res) => {
          console.log('调用成功!')
        },
        // 失败回调
        fail: (res) => {
          console.log('调用失败!')
        }
      });
    },
    previewPostImg(postDto, index) {
      console.log('预览图片', postDto, index)
      let urls = postDto.facadePicture.split(',')
      uni.previewImage({
        current: index,
        urls: urls
      })
    },
  }
}

// mixin.js
export const bhTabMixin = {
  initData(currentTabIndex = 0) {
    return {
      // tab列表
      // tabList: [{ id: -1, name: '店铺', list: [], param: { pageNum: 1, pageSize: 10 } },
      // { id: 0, name: '发帖', list: [], param: { pageNum: 1, pageSize: 10 } },
      // { id: 0, name: '我的是的', list: [], param: { pageNum: 1, pageSize: 10 } }],
      // tabList: [{ id: -1, name: '店铺', list: [], param: { pageNum: 1, pageSize: 10 } },
      // { id: 0, name: '综合', list: [], param: { pageNum: 1, pageSize: 10 } },
      // ...constant_menus.leafMenuList()],
      currentTabIndex: currentTabIndex,
      // more 加载前 loading	加载中  no-more	没有更多数据
      // tabLoadingStatus: 'more',
      tabLoadingStatus: 'loading'
    }
  },
  methods: {
    changeTab(tabIndex) {
      console.log('选择tab，', tabIndex)
      this.currentTabIndex = tabIndex
      if (this.currentTabIndex == tabIndex) {
        this.getTabData(tabIndex, true)
      } else {
        this.getTabData(tabIndex, false)
      }
    },
    contentNoMore(ingorePageNum = false) {
      console.log('根据pageNum判断是否展示，没有跟多了，标识', this.tabList[this.currentTabIndex].param.pageNum)
      if (ingorePageNum) {
        return this.tabList[this.currentTabIndex].list.length > 0
      } else {
        return this.tabList[this.currentTabIndex].param.pageNum === -1
          && this.tabList[this.currentTabIndex].list.length > 0
      }
    },
    scrolltolower() {
      console.log('tab内容触底了')
      this.getTabData(this.currentTabIndex, false)
    },
    // 从后台获取tab内容
    getTabData(tabIndex, initPageNum, callback = (res) => { }) {
      let that = this
      let param = this.tabList[tabIndex].param
      let list = this.tabList[tabIndex].list
      if (initPageNum) {
        // 初始化页码，数据
        param.pageNum = 1
        list = []
      }
      if (param.pageNum == -1) {
        console.log('没有更多数据，直接返回')
        return;
      }

      if (this.requestParam) {
        param = Object.assign(param, this.requestParam())
      }
      this.tabLoadingStatus = 'loading'
      this.requestData && this.requestData(param).then(res => {
        
        callback(res)
        if (res.code == 200) {
          if (res.data.records && res.data.records.length > 0) {
            // 后台返回数据不为空，添加到list中，页数加1
            console.log('后台返回数据length', res.data.records.length)
            list = param.pageNum == 1 ? res.data.records : list.concat(res.data.records)
            that.tabList[tabIndex].list = list
            that.tabList[tabIndex].total = res.data.total
            that.tabList[tabIndex].size = res.data.size
            that.tabList[tabIndex].pages = res.data.pages
            console.log('最新数据list', list)
            that.tabList[tabIndex].param.pageNum = that.tabList[tabIndex].param.pageNum + 1
            that.tabLoadingStatus = 'more'
          } else if (!res.data.records && res.data && res.data.length && res.data.length > 0) {
            console.log('后台返回数据length', res.data.length)
            list = res.data
            that.tabList[tabIndex].list = list
            that.tabList[tabIndex].total = res.data.total
            that.tabList[tabIndex].size = res.data.size
            that.tabList[tabIndex].pages = res.data.pages
            console.log('最新数据list', list)
            that.tabList[tabIndex].param.pageNum = -1
            that.tabLoadingStatus = 'no-more'
          } else {
            that.tabList[tabIndex].param.pageNum = -1
            that.tabList[tabIndex].list = list
            that.tabList[tabIndex].total = res.data.total
            that.tabList[tabIndex].size = res.data.size
            that.tabList[tabIndex].pages = res.data.pages
            if(that.tabList[tabIndex].list.length <= 0){
              that.tabLoadingStatus = 'more'
            }else{
              that.tabLoadingStatus = 'no-more'
            }
          }
        }else{
          check_utils.showCustToast(res.msg)
          that.tabLoadingStatus = 'more'
        }
      })
    },
  }
}

